import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { Row, Col, Tabs, Button, Card, Carousel, Tag, Spin, Rate, Divider, Image, List, Avatar } from 'antd';
import { EnvironmentOutlined, WifiOutlined, CoffeeOutlined, CarOutlined, CheckCircleOutlined } from '@ant-design/icons';
import styled from 'styled-components';
import MainLayout from '../../components/Layout/MainLayout';
import { getHotelDetail, getHotelRooms, getHotelReviews } from '../../api/hotelApi';
import { Hotel, Room, HotelReview } from '../../api/types';

const { TabPane } = Tabs;

const PageContainer = styled.div`
  padding: 20px 0;
`;

const HotelName = styled.h1`
  font-size: 28px;
  font-weight: 600;
  margin-bottom: 10px;
`;

const HotelAddress = styled.div`
  color: #666;
  font-size: 14px;
  margin-bottom: 15px;
  display: flex;
  align-items: center;
`;

const MainCarousel = styled(Carousel)`
  .slick-slide {
    text-align: center;
    height: 400px;
    line-height: 400px;
    background: #f0f0f0;
    overflow: hidden;
    border-radius: 8px;
  }

  .carousel-image {
    width: 100%;
    height: 400px;
    object-fit: cover;
  }
`;

const RoomCard = styled(Card)`
  margin-bottom: 20px;
  transition: all 0.3s;
  
  &:hover {
    box-shadow: 0 4px 12px rgba(0,0,0,0.1);
  }
`;

const RoomTitle = styled.h3`
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 10px;
`;

const RoomInfo = styled.div`
  display: flex;
  margin-bottom: 15px;
  flex-wrap: wrap;
`;

const RoomInfoItem = styled.div`
  margin-right: 20px;
  margin-bottom: 8px;
  color: #666;
  font-size: 14px;
  display: flex;
  align-items: center;
  
  .anticon {
    margin-right: 5px;
  }
`;

const PriceTag = styled.div`
  font-size: 20px;
  font-weight: 600;
  color: #ff4d4f;
`;

const OriginalPrice = styled.span`
  text-decoration: line-through;
  color: #999;
  font-size: 14px;
  margin-left: 8px;
  font-weight: normal;
`;

const HotelTags = styled.div`
  margin-bottom: 15px;
`;

// 设施图标映射
const facilityIcons = {
  wifi: <WifiOutlined />,
  breakfast: <CoffeeOutlined />,
  parking: <CarOutlined />
};

const HotelDetailPage: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  
  const [hotel, setHotel] = useState<Hotel | null>(null);
  const [rooms, setRooms] = useState<Room[]>([]);
  const [reviews, setReviews] = useState<HotelReview[]>([]);
  const [loading, setLoading] = useState(true);
  
  useEffect(() => {
    const fetchHotelData = async () => {
      if (!id) return;
      
      setLoading(true);
      try {
        // 并行请求酒店详情、房间和评论数据
        const [hotelRes, roomsRes, reviewsRes] = await Promise.all([
          getHotelDetail(id),
          getHotelRooms(id),
          getHotelReviews(id)
        ]);
        
        setHotel(hotelRes.data);
        setRooms(roomsRes.data);
        setReviews(reviewsRes.data.list);
      } catch (error) {
        console.error('获取酒店详情失败', error);
      } finally {
        setLoading(false);
      }
    };
    
    fetchHotelData();
  }, [id]);
  
  // 处理预订按钮点击
  const handleBookRoom = (roomId: string) => {
    navigate(`/order?hotelId=${id}&roomId=${roomId}`);
  };
  
  if (loading) {
    return (
      <MainLayout>
        <div style={{ textAlign: 'center', padding: '100px 0' }}>
          <Spin size="large" />
        </div>
      </MainLayout>
    );
  }
  
  if (!hotel) {
    return (
      <MainLayout>
        <div style={{ textAlign: 'center', padding: '100px 0' }}>
          <h2>未找到该酒店</h2>
          <Button type="primary" onClick={() => navigate(-1)}>返回上一页</Button>
        </div>
      </MainLayout>
    );
  }
  
  return (
    <MainLayout>
      <PageContainer className="container">
        <Row gutter={[24, 24]}>
          <Col span={24}>
            <HotelName>{hotel.name}</HotelName>
            <HotelAddress>
              <EnvironmentOutlined style={{ marginRight: 8 }} />
              {hotel.address}
            </HotelAddress>
            
            <HotelTags>
              <Rate disabled defaultValue={hotel.starRating} style={{ marginRight: 16 }} />
              {hotel.tags.map((tag, index) => (
                <Tag color="blue" key={index}>{tag}</Tag>
              ))}
            </HotelTags>
          </Col>
          
          <Col span={24}>
            <MainCarousel autoplay>
              {hotel.images.map((image, index) => (
                <div key={index}>
                  <img src={image} alt={`${hotel.name}_${index}`} className="carousel-image" />
                </div>
              ))}
            </MainCarousel>
          </Col>
          
          <Col span={24}>
            <Tabs defaultActiveKey="rooms">
              <TabPane tab="房型与价格" key="rooms">
                {rooms.length > 0 ? (
                  rooms.map(room => (
                    <RoomCard key={room.id}>
                      <Row gutter={16}>
                        <Col xs={24} sm={8} md={6}>
                          <Image
                            src={room.imageUrls[0]}
                            alt={room.name}
                            style={{ width: '100%', height: 150, objectFit: 'cover' }}
                          />
                        </Col>
                        <Col xs={24} sm={16} md={18}>
                          <RoomTitle>{room.name}</RoomTitle>
                          <RoomInfo>
                            <RoomInfoItem>
                              <span>床型: {room.bedType}</span>
                            </RoomInfoItem>
                            <RoomInfoItem>
                              <span>面积: {room.area}㎡</span>
                            </RoomInfoItem>
                            <RoomInfoItem>
                              <span>最多住: {room.maxGuests}人</span>
                            </RoomInfoItem>
                            {room.wifi && (
                              <RoomInfoItem>
                                <WifiOutlined /> 免费Wi-Fi
                              </RoomInfoItem>
                            )}
                            {room.breakfast && (
                              <RoomInfoItem>
                                <CoffeeOutlined /> 含早餐
                              </RoomInfoItem>
                            )}
                          </RoomInfo>
                          
                          <Row justify="space-between" align="middle">
                            <Col>
                              <PriceTag>
                                ¥{room.discount ? Math.floor(room.price * room.discount / 100) : room.price}
                                {room.discount && (
                                  <OriginalPrice>¥{room.price}</OriginalPrice>
                                )}
                              </PriceTag>
                            </Col>
                            <Col>
                              <Button type="primary" onClick={() => handleBookRoom(room.id)}>
                                立即预订
                              </Button>
                            </Col>
                          </Row>
                        </Col>
                      </Row>
                    </RoomCard>
                  ))
                ) : (
                  <div style={{ textAlign: 'center', padding: '20px 0' }}>
                    暂无可预订房间
                  </div>
                )}
              </TabPane>
              
              <TabPane tab="酒店详情" key="details">
                <Card>
                  <h3>酒店介绍</h3>
                  <p>{hotel.description || '暂无详细介绍'}</p>
                  
                  <Divider />
                  
                  <h3>酒店设施</h3>
                  <List
                    grid={{ gutter: 16, column: 3 }}
                    dataSource={hotel.facilities || []}
                    renderItem={item => (
                      <List.Item>
                        <div style={{ display: 'flex', alignItems: 'center' }}>
                          <CheckCircleOutlined style={{ color: '#52c41a', marginRight: 8 }} />
                          {item}
                        </div>
                      </List.Item>
                    )}
                  />
                </Card>
              </TabPane>
              
              <TabPane tab="用户评价" key="reviews">
                <Card>
                  {reviews.length > 0 ? (
                    <List
                      itemLayout="horizontal"
                      dataSource={reviews}
                      renderItem={review => (
                        <List.Item>
                          <List.Item.Meta
                            avatar={<Avatar src={review.avatar || 'https://joeschmoe.io/api/v1/random'} />}
                            title={<span>{review.username}</span>}
                            description={
                              <div>
                                <Rate disabled defaultValue={review.rating} />
                                <p>{review.comment}</p>
                                {review.images && review.images.length > 0 && (
                                  <div style={{ marginTop: 10 }}>
                                    {review.images.map((img, index) => (
                                      <Image
                                        key={index}
                                        src={img}
                                        width={100}
                                        height={100}
                                        style={{ marginRight: 8, objectFit: 'cover' }}
                                      />
                                    ))}
                                  </div>
                                )}
                              </div>
                            }
                          />
                        </List.Item>
                      )}
                    />
                  ) : (
                    <div style={{ textAlign: 'center', padding: '20px 0' }}>
                      暂无评价
                    </div>
                  )}
                </Card>
              </TabPane>
            </Tabs>
          </Col>
        </Row>
      </PageContainer>
    </MainLayout>
  );
};

export default HotelDetailPage; 